0

I want to use awk to print all values in a delimited string with a static suffix appended to each one.

Input:

stack,over,flow

Delimiter:

Comma

Output:

stack suffix, over suffix, flow suffix
2
awk -F ',' -v OFS=',' -vpre="prefix" -vsuf="suffix" \
    '{ for (i=1;i<=NF;++i) $i = pre $i suf; print }'

For the input

unix,and,linux

this would produce

prefixunixsuffix,prefixandsuffix,prefixlinuxsuffix

The awk program modifies each field in a loop by adding a prefix and a suffix. The prefix and suffix strings are passed into the awk programs through assignments to the pre and suf variables on the command line.

To add a space as prefix and the string suffix (with an initial space) as suffix, you would use

awk -F ',' -v OFS=',' -vpre=" " -vsuf=" suffix" \
    '{ for (i=1;i<=NF;++i) $i = pre $i suf; print }'

which produces

 unix suffix, and suffix, linux suffix
  • Hi @Kusalananda, its awesome, and one more doubt, If I don't want the comma, how can I remove that? like stack suffix over suffix flow suffix or replace with some other value – Bhuvanesh Nov 26 '18 at 21:41
  • @SQLadmin Modify the output field separator (OFS) on the command line. For example, remove -v OFS completely to get space-separated output. – Kusalananda Nov 26 '18 at 21:45
2

Another Awk variant - making use of the internal output separators to avoid an explicit loop:

awk -F, -v s=' suffix' 'BEGIN{OFS= s FS " "; ORS= s RS} {$1=$1} 1'

ex.

echo 'stack,over,flow' | awk -F, -v s=' suffix' 'BEGIN{OFS= s FS " "; ORS= s RS} {$1=$1} 1'
stack suffix, over suffix, flow suffix

For space separated output you can append the default output field separator to the suffix

$ echo 'stack,over,flow' | awk -F, -v s=' suffix' 'BEGIN{OFS= s OFS; ORS= s RS} {$1=$1} 1'
stack suffix over suffix flow suffix
1
awk -F , '{print $1" suffix",  $2" suffix",  $3" suffix"}' OFS=", " suffix

awk -F , Sets the field separator as ,

print $1" suffix", and so on and so forth prints a space and then suffix after the value

OFS=", " Sets the output field separator as a comma with a space.

Output:

 stack suffix, over suffix, flow suffix
  • Hey @Nasir, thanks, but in my case, there can be multiple values in input. So we need to use -F to get all values print with suffix.I don't know how to achieve this. – Bhuvanesh Nov 26 '18 at 21:37
  • @SQLadmin The other answer works better. In the future, you need to specify that information in your question so that it can be accounted for. – Nasir Riley Nov 26 '18 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.