'bourne shell: for loop with iterating comma seperated strings

I have text files including TV channel names. I want to remove some parts in the names of the tv channels. F.i. if a channel name is: BBC 1 HD, I want to delete " HD" at the end. Important here is the space before HD. I put the string patterns which should be removed in the string variable 'StrDelList'. So do I have multiple channel lists and therefor: I want to make use (in a /bin.sh file) of a for-loop with a comma seperated list of strings.

What I have so far:

Field_ORG=$IFS
StrDelList=" HD, HEVC, FHD, (EVENT ONLY), (ONLY DURING LIVE MATCHES)"
for x in $StrDelList; do sed -i "s/$x//g" $FILE1; done
IFS=$Field_ORG

However the output is not what I expected due to the space at the beginning of every string in the list. It is more clear when I change the last command in:

for x in $StrDelList; do $x $FILE1; done

The output will be:

HD
HEVC
FHD
(EVENT ONLY)
(ONLY DURING LIVE MATCHES)

and it shoud be (mind the beginning space):

 HD
 HEVC
 FHD
 (EVENT ONLY)
 (ONLY DURING LIVE MATCHES)

What did I wrong?



Solution 1:[1]

Suggesting to use an array, as in the following:

Each array element may contain spaces and brackets ( )

Than loop/iterate over each element in array.

StrDelArray=(" HD" " HEVC"  " FHD" " (EVENT ONLY)" " (ONLY DURING LIVE MATCHES)")
for strDel in ${StrDelArray[@]}; do 
  sed -i "s/$strDel//g" $FILE1;
done

Another option that executes all the replacements with single sed command (no loop).

Collect all the target strings into a single ored RegExp

Assuming there is no string @@@@@ in your file

StrDelArray=(" HD" " HEVC"  " FHD" " (EVENT ONLY)" " (ONLY DURING LIVE MATCHES)")
sedTargets=$(printf "\\|%s" ${StrDelArray[@]})
sed -i "s/@@@@@@$sedTargets//g" $FILE1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1