I am attempting to write a small shell script that firstly defines a file name using date and then runs two sed commands which strip out certain characters.
My code is as follows:
filename=/var/local/file1/tsv_`date '+%d%m%y'`.txt
sed -i 's/\("[^,]*\)[,]\([^"]*"\)/\1\2/g' '&filename'
sed -i 's/\"//g' '&filename'
I am getting the following error:
sed: can't read &filename: No such file or directory
sed: can't read &filename: No such file or directory
Question is, how can I pass this filename variable into the sed command?
Thanks
For replacing a variable value using sed, we first need to understand how sed works and how we can replace a simple string in any file using sed. In this syntax, you just need to provide the string you want to replace at the old string and then the new string in the inverted commas.
The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.
The p command (print) The p command prints out the pattern space to STDOUT. The p command is mostly only used in conjunction with the -n option to sed, because, otherwise, printing each line is sed's default behaviour.
The reason why shell variables are not expanded within single quotes is that we used single quotes under the sed command. Double quotation marks are used in the sed command to allow quick fix shell variable expansion.
When doing shell scripting, for referencing variables the & (ampersand) is not used, but the $ (dollar sign):
filename=/var/local/file1/tsv_`date '+%d%m%y'`.txt
sed -i 's/\("[^,]*\)[,]\([^"]*"\)/\1\2/g' "$filename"
sed -i 's/\"//g' "$filename"
Also when referencing variables, double quotes must be used, if not, bash won't interpret the meaning of the $ sign.
You want to use double-quotes when passing a variable to sed
. If you use single quotes, the variable will be read literally.
To use a shell variable in a command, preface it with a dollar sign ($). This tells the command interpreter that you want the variable's value, not its name, to be used.
filename=/var/local/file1/tsv_`date '+%d%m%y'`.txt
sed -i 's/\("[^,]*\)[,]\([^"]*"\)/\1\2/g' "$filename"
sed -i 's/\"//g' "$filename"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With