简体   繁体   中英

awk print $0 with newline separated column values

Input:

"prefix_foo,prefix_bar"

Expected Output:

foo
bar

This is what I've so far.

$ echo "PREFIX_foo,PREFIX_bar" | awk '/PREFIX_/{x=gsub("PREFIX_", ""); print $0 }'
foo,bar

I'm unable to figure out how to print foo and bar separated by a newline. Thanks in advance!

EDIT:

  • Length of input is unknown so there can be more than 2 words separated by comma.
  • This question is more towards learning awk language, not alternative gnu utils.

You may not need awk for this. Here is pure bash solution:

s="prefix_foo,prefix_bar"
s="${s//prefix_/}"
s="${s//,/$'\n'}"
echo "$s"

foo
bar

Here is one liner gnu sed for the same:

sed 's/prefix_//g; s/,/\n/g' <<< "$s"

foo
bar

EDIT: 2nd solution Adding more generic solution here as per OP's comments, this will Look for every field and check if its having prefix then it will print that column's 2nd part(after _ one).

echo "prefix_foo,etc,bla,prefix_bar" | 
awk '
BEGIN{
  FS=OFS=","
}
{
  for(i=1;i<=NF;i++){
    if($i~/prefix/){
      split($i,array,"_")
      val=(val?val OFS:"")array[2]
    }
  }
  if(val){
    print val
  }
  val=""
}'

To print output field values in new line try:

echo "prefix_foo,etc,bla,prefix_bar" | 
awk '
BEGIN{
  FS=OFS=","
}
{
  for(i=1;i<=NF;i++){
    if($i~/prefix/){
      split($i,array,"_")
      print array[2]
    }
  }
}
'


1st solution: For simple case(specific to shown samples) could you please try following.

awk -F'[_,]' '/prefix_/{print $2,$4}'  Input_file

OR

echo "prefix_foo,prefix_bar" | awk -F'[_,]' '/prefix_/{print $2,$4}'

Just trying out awk

 echo "PREFIX_foo,PREFIX_bar" | awk -F, -v OFS="\n" '{gsub(/PREFIX_/,""); $1=$1}1'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM