balázios
balázios

Reputation: 17

Find and Replace with awk

I have this value, cutted from .txt:

,Request Id,dummy1,dummy2,dummyN

I am trying to find and replace the space with "_", like this:

#iterator to read lines of txt
#if conditions
trim_line=$(echo "$user" | awk '{gsub(" ", "_", $0); print}')
echo $trim_line

but the echo is showing:

Id,dummy1,dummy2,dummyN

Expected output:

,Request_Id,dummy1,dummy2,dummyN

Where is my bug?

EDIT: The echo of user is not the expected, it is:

Id,dummy1,dummy2,dummyN

And should be:

,Request Id,dummy1,dummy2,dummyN

To do this operation I am using:

for user in $(cut -d: -f1 $FILENAME)
do (....) find/replace

Upvotes: 0

Views: 2012

Answers (3)

Tom Fenech
Tom Fenech

Reputation: 74596

Your problem is your use of a for loop to read the contents of your file. The shell splits the output of your command substitution $(cut -d: -f1 $FILENAME) on white space and you have one in the middle of your line, so it breaks.

Use a while read loop to read the file line by line:

while IFS=: read -r col junk; do
    col=${col// /_}
    # use $col here
done < "$FILENAME"

As others have mentioned, there's no need to use an external tool to make the substitution.

...That said, if you don't plan on doing something different (e.g. executing other commands) with each line, then the best option is to use awk:

awk -F: '{ gsub(/ /, "_", $1); print $1 }' "$FILENAME"

The output of this command is the first column of your input file, with the substitution made.

Upvotes: 0

P....
P....

Reputation: 18351

You can try bash search and replace substring :

 echo $user
,Request Id,dummy1,dummy2,dummyN
 echo ${user// /_}                   ## For all the spaces
,Request_Id,dummy1,dummy2,dummyN
 echo ${user/ /_}                   ## For first match

This will replace all the blank spaces with _. Note that here two / are used after user. This is to do the search and replace operation on whole text. If you put only one / then search and replace would be done over first match.

Upvotes: 1

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

If your data is already in an environment variable, the fastest way is to directly use built-in bash replacement feature:

echo "${user// /_/}"

With awk, set the separator as , or the space character will be interpreted as the separator.

echo ",Request Id,dummy1,dummy2,dummyN" | awk -F, '{gsub(" ", "_", $0); print}'

,Request_Id,dummy1,dummy2,dummyN

note: if it's just to replace a character in a raw string (no tokens, no fields), bash, sed and tr are best suited.

Upvotes: 0

Related Questions