If I wanted to search for a line in a file and append a string to the end of that line, how can I go about it? IE:
file=?
I want to search for file=?
and replace the question mark with a file path. The file path is located in a variable $FILEPATH
file=$FILEPATH
Thanks!
EDIT
sed -i -f "s,file=\?,file=$FILEPATH,g"
The above works well and is what I'm looking for but is there a way to replace the question mark? With the code above if I have the following:
FILEPATH=/file/path
Properties file:
something=?
file=?
The replacement produces:
Properties file:
something=?
file=/file/path?
Is there a way to replace the ?
completely?
I'd use sed for that:
sed -i "s/file=?/file=$FILEPATH/g" your_file
If your $FILEPATH
has /
then use a different sed
separator, something like:
sed -i "s,file=?,file=$FILEPATH,g"
Don't escape your question mark
[jaypal:~/Temp] cat temp
file=?
file=?
[jaypal:~/Temp] echo $filepath
/usr/bin
[jaypal:~/Temp] sed -e 's_file=?_file='$filepath'_g' temp
file=/usr/bin
file=/usr/bin
Also to make inline changes I would recommend to use the following -
[jaypal:~/Temp] sed -ibak 's_file=?_file='$filepath'_g' temp
[jaypal:~/Temp] ls temp*
temp tempbak
[jaypal:~/Temp] cat temp
file=/usr/bin
file=/usr/bin
[jaypal:~/Temp] cat tempbak
file=?
file=?
This will make a backup copy of your original file before making any changes. In case if anything goes wrong you will have your original copy protected.
If you are using Bash, you can simply use Bash builtins and substitutions instead of sed:
#!/bin/bash
FILEPATH="/file/path"
while read line; do
echo "${line/file=\?/${line/\?/}$FILEPATH}"
done < yourfile
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.