1

I have a variable VAR="XYZ YZA ZAB" declared and I would like to append some strings next to all the words in that variable.

For example: I want to append .file1 to each space-separate substring in XYZ YZA ZAB.

The output of variable should be as below without any for loop or anything.

VAR="XYZ.file1 YZA.file1 ZAB.file1"

I am sure awk can be used, but I am not aware of how to use it for this purpose.

3

With ksh93:

VAR2=${VAR//+([^[:space:]])/\1.file1}

Same with zsh:

set -o extendedglob
VAR2=${VAR//(#m)[^[:space:]]##/$MATCH.file1}

POSIXly:

VAR2=$(printf '%s\n' "$VAR" | sed 's/[^[:space:]]\{1,\}/&.file1/g')

(beware it strips trailing newline characters if any in $VAR).

They all substitute sequences of one or more (+(...), ##, \{1,\}) characters other than white space ones ([^[:space:]]) with the same thing (\1, $MATCH, &) and .file1 appended.

Or you could split and join if you don't care about preserving the amount of white space between words and words are separated by SPC, TAB and NL (and not other whitespace characters) only:

unset IFS # default IFS of SPC+TAB+NL
set -o noglob # disable glob
set -- $VAR # split+glob without glob
for i do
  set -- "$@" "$i.file1" # add suffix
  shift
done
VAR2="$*" # join with space

With shells with array support, you may want to use an array variable instead of a scalar one. With rc/es/zsh/ksh93/bash/mksh/yash:

VAR=(XYZ YZA ZAB)

Then adding .file1 to each element (which this time may contain white space themselves) is just a matter of:

VAR2=($VAR^.file1) # rc, es
VAR2=($^VAR.file1) # zsh
VAR2=("${VAR[@]/*/\0.file1}") # ksh93
VAR2=("${VAR[@]/%/.file1}") # bash
1

The simple solution will be to use the shell splitting capability (with a default IFS):

$ set -f; printf '%s.file1 ' $var; echo
XYZ.file1 YZA.file1 ZAB.file1

Understand that that will collapse repeated spaces/tabs to one and that it will remove leading and trailing white-space. The set -f will avoid problems with filenames that contain glob characters (* ? or [). The printed string in this case will have an additional space.

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.