2

I'm trying to do something in bash with sed that is proving to be extremely difficult.

I have a bash script that takes as its first argument a date.

The code want to change a line in a text file to include the passed date. Here's the code

#!/bin/bash

cq_fname="%let outputfile="/user/cq_"$1".csv";"

sed "29s/.*/\"$ct_fname\"/" file1.sas > file2.sas

This script fails on the third line, I get something about a garbled command. Does anybody know a clever way to get this to work? How can I get a forward slash in quotes in sed?

sarnold
  • 102,305
  • 22
  • 181
  • 238
user788171
  • 16,753
  • 40
  • 98
  • 125

4 Answers4

6

You can use any character in place of the /, so just pick one that is not in $ct_fname:

sed "29s|.*|\"$ct_fname\"|" file1.sas > file2.sas
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
2

The syntax highlighting here should be a good indicator of what your problem is -- you've got several strings smashed together with content that isn't in the strings. Try replacing this:

cq_fname="%let outputfile="/user/cq_"$1".csv";"

with this:

cq_fname="%let outputfile=\"/user/cq_$1.csv\";"

I escaped the " inside the string with \ characters and removed the " characters that felt like they probably don't exist in the filename.

Alok suggests using a different character for the replacement command -- that's necessary.

Also, you need to use the same variable name in both the assignment and the string. (D'oh!)

The final script is:

#!/bin/bash
cq_fname="%let outputfile=\"/user/cq_$1.csv\";"
sed "29s|.*|$cq_fname|" file1.sas > file2.sas

I found the mis-matched variable names by adding set -x to the top of the script; it showed the execution output of the script along the way.

Broken:

$ ./replace 
+ cq_fname='%let outputfile="/user/cq_.csv";'
+ sed '29s|.*||' file1.sas

Fixed:

$ ./replace 
+ cq_fname='%let outputfile="/user/cq_.csv";'
+ sed '29s|.*|%let outputfile="/user/cq_.csv";|' file1.sas

set -x is a superb little debugging tool, when you need it.

Community
  • 1
  • 1
sarnold
  • 102,305
  • 22
  • 181
  • 238
0

On every other set of quotes, use ' (single quote) instead of " (double quote).

  • Single-quotes may not work in the `.sas` file format -- and the `$1` needs to be interpreted by the shell, so I don't think replacing the _outer_ quotes with `'` will work either. – sarnold Jun 21 '12 at 21:58
0

This might work for you:

cq_fname='%let outputfile="/user/cq_.csv";'
sed '29c\'"$cq_fname" file1.sas > file2.sas
potong
  • 55,640
  • 6
  • 51
  • 83