简体   繁体   中英

How can I write bash script that returns line from file which starts from the begining untill specific symbol?

I have simple file:

line1(sometext)
line222(other_text)
line333(other text)

I pass to script in arguments part of word before symbol "(" How can I chech using grep command if this line exists ? for example I pass in arguments word line222 - it returns line222(other_text)

but it I pass "line2" - it says that line was not found Right now I have this code, that gives wrong result if I type one symbol

if ! grep home "myfile.txt" | grep -- "$1"; then
   echo "Line doesn't exist"
fi

You can verify whether the certain line exists or doesn't exist in your file as follows:

if [[ $(grep "^${1}" "myfile.txt") ]]; then
    echo "Line starts with \"${1}\" exists"
else
    echo "Line starts with \"${1}\" doesn't exist"
fi

or if you just want print the output info when it doesn't exist, then this may help:

if [[ ! $(grep "^${1}" "myfile.txt") ]]; then
    echo "Line starts with \"${1}\" doesn't exist"
fi

grep "^${1}" searches for the text pattern, ^${1} means starting with the variable that you pass to your script. [[ ... ]] tests the condition (bash way) and ! sign negates the test condition.

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