Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass filename variable into sed command

Tags:

bash

shell

unix

sed

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

like image 818
Ben Avatar asked Aug 21 '15 08:08

Ben


People also ask

How do you replace a variable in a file using sed?

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.

Can you use sed on a variable?

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.

What is $P in sed?

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.

How do you expand a variable in sed?

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.


2 Answers

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.

like image 128
Eduardo Yáñez Parareda Avatar answered Sep 23 '22 01:09

Eduardo Yáñez Parareda


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"
like image 37
davidcondrey Avatar answered Sep 24 '22 01:09

davidcondrey