sed, foward slash in quotes

徘徊边缘 提交于 2019-12-29 08:11:06

问题


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?


回答1:


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



回答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.




回答3:


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




回答4:


This might work for you:

cq_fname='%let outputfile="/user/cq_.csv";'
sed '29c\'"$cq_fname" file1.sas > file2.sas


来源:https://stackoverflow.com/questions/11147323/sed-foward-slash-in-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!