简体   繁体   中英

How sed command used in shell script

I have shell script where I am using SED command, I am Reading file and remove all character after HELLO from each statement, But still I am getting null value

file=commit.txt
    while IFS= read line
    do
            commitid=$line | sed "s/  HELLO.*'[^']*'/ /"
             echo $line | sed "s/  HELLO.*'[^']*'/ /"   /* Not removing character*/
            echo $commitid /* Returning null*/
    done <"$file"

my file has 2 statement

dummy statement Hello world 
dummy 1 statement Hello Mike

expected output

dummy statement 
dummy 1 statement

How to fix this issue?

It is a job of simple sed as follows.

file="commit.txt"
sed 's/Hello.*//g' "$file"

What you need is "command substitution" in bash. For this you have to enclose your command with $()

while IFS= read line
do
    val1=$(echo "$line"|sed 's/HALLO/TEST/')
    val2=$(echo "$val1"|sed 's/TEST/XYZ/')
    echo $val2
done < test.txt

I used a simpler sed expression to see it works with my text file. As you can see, I first replace HALLO with TEST and in next line TEST with XYZ. So you can see that the variable content is handled and passed to the next evaluation.

Input:

eins HALLO zwei
eins HALLO zwei
eins HALLO zwei
eins HALLO zwei

Output:

eins XYZ zwei
eins XYZ zwei
eins XYZ zwei
eins XYZ zwei

Update: After you provide your input data, the script can be:

while IFS= read line
do
    val=$(echo "$line"|sed 's/Hello.*$//')
    echo $val
done < test.txt

But indeed no need for a script here:

sed 's/Hello.*$//' test.txt > output.txt

did the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM