1

I have a file like this -

 1,[test1] Joe,OK
 2,[test2] Jack,OK
 3,[test3] Tom,FAIL

I am printing the file like this -

cat file | awk -F"," '{ print "||"  $1 "||" $2 "||" $3 "||" }' 

I would like the output file like this -

|| 1 || Joe  || OK ||
|| 2 || Jack || OK ||
|| 3 || Tom  || FAIL ||

i.e. [test1] Joe is modified to Joe how can we do something like this on each column.

echo "[test1] Joe" | sed 's/\[.*\]\s//g'

Which gives me only Joe how can I combined this with the other columns?

1
  • 2
    Does the input file really contain a leading space? I have a suspicion it's doesn't.. Commented Mar 1, 2013 at 10:20

4 Answers 4

3

In awk with the correct spacing:

$ awk -F, '{split($2,a," ");printf "||%s || %-4s || %s ||\n",$1,a[2],$3}' file
|| 1 || Joe  || OK ||
|| 2 || Jack || OK ||
|| 3 || Tom  || FAIL ||

You was almost there with your attempt, you should take a look at the printf and split functions.

Sign up to request clarification or add additional context in comments.

Comments

2

With sed:

   sed 's/\[[^]]*\]//;s/^/|| /;s/$/ ||/;s/,/ || /g' input

Output

|| 1 ||  Joe || OK ||
|| 2 ||  Jack || OK ||
|| 3 ||  Tom || FAIL ||

To do in-place start with sed -i

2 Comments

This doesn't add the field separator || to the start and end of each line.
Well it's as close Guru's and sarathi I guess. sed probably isn't the best tool for this.
0

One way:

awk -F, '{$1=OFS""$1;$NF=$NF""OFS;sub(/.* /,"",$2);}1' OFS=" || " file

On running the above:

 ||  1 || Joe || OK ||
 ||  2 || Jack || OK ||
 ||  3 || Tom || FAIL ||

Comments

0
awk -F"," '{gsub(/,\[.*?\]|,|^|$/," || ",$0) }1' your_file

or

perl -plne 's/^|,/ || /g;s/\[.*?\]//g' your_file

tested below:

> cat temp
1,[test1] Joe,OK
2,[test2] Jack,OK
3,[test3] Tom,FAIL
> perl -plne 's/^|,|$/ || /g;s/\[.*?\]//g' temp
 || 1 ||  Joe || OK || 
 || 2 ||  Jack || OK || 
 || 3 ||  Tom || FAIL ||
> awk -F"," '{gsub(/,\[.*?\]|,|^|$/," || ",$0) }1' temp
 || 1 ||  Joe || OK || 
 || 2 ||  Jack || OK || 
 || 3 ||  Tom || FAIL || 
> 

If you want to replace the file inplace use:

perl -i -plne 's/^|,|$/ || /g;s/\[.*?\]//g' your_file

4 Comments

Missing the closing separator || and spacing is off.
Modified according to the comment.
Your attempted regex hacks still don't fix the spacing issue!
Ok @Sudo...you are the best.i am upvoting you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.