Reputation: 341
I'm really new in awk language and I'm suprised of all the power it has. (I discovered this today), because I have a file in this format:
test1;test2;test3;test4;test5;test6;test7
I need to output this in a new file and get this as result:
test1;test2;test3;test4 test5;test6;test7
Basically add ' ' between $4 and $5. I know there is a lot of questions about this but I'm not able to do what I want.
I was testing this code that I found somewhere here:
for (i=1;i<=3;i++)
printf "%s;", $i
n = split($0,tmp,/ +/)
for (i=6;i>=8;i++)
printf ";%s", tmp[n-i]
print ""
}
But I get as output something like:
test1;test2;test3;test4;test5;test6;;;
Can you please tell my what I'm doing wrong? and, there is another simple method like one-line code in awk to do this? Thank you in advance
Upvotes: 2
Views: 923
Reputation: 9256
I'd go with sed on this one. On the basis that the issue is "replace the 4th ; character" you can use this:
sed 's/;/ /4' <inputfile>
That'll output the result to stdout, or you can use "sed -i" to do it in place.
See http://www.gnu.org/software/sed/manual/html_node/The-_0022s_0022-Command.html
Upvotes: 5
Reputation: 47249
If you're using GNU awk you could use a similar solution to what chooban suggested:
awk '{ $0=gensub(";", " ", "4") } 1'
The 1
at the end invokes the default block: { print $0 }
.
Upvotes: 2
Reputation: 185881
Try this :
echo "test1;test2;test3;test4;test5;test6;test7" | awk -F';' '{
for (i=1; i<=NF; i++)
printf "%s%s", $i, (i == 4) ? " " : ";"
}'
test1;test2;test3;test4 test5;test6;test7
Upvotes: 3