Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 将换行符转换为实际字符串_Regex_Awk_Sed_String Matching_Tr - Fatal编程技术网

Regex 将换行符转换为实际字符串

Regex 将换行符转换为实际字符串,regex,awk,sed,string-matching,tr,Regex,Awk,Sed,String Matching,Tr,我有这样一个文件: #!/bin/bash echo $(date "+%F %R:%S") ":: yum update" /usr/bin/yum update -y 我想将其转换为带引号的字符串: "#!/bin/bash\necho $(date \"+%F %R:%S\") \":: yum update\"\n/usr/bin/yum update -y\n" 我使用的任何方法都匹配换行符,但会将它们转换为换行符而不是\n。因此,这些例子: sed 's/\n/\n/g' fil

我有这样一个文件:

#!/bin/bash
echo $(date "+%F %R:%S") ":: yum update"
/usr/bin/yum update -y
我想将其转换为带引号的字符串:

"#!/bin/bash\necho $(date \"+%F %R:%S\") \":: yum update\"\n/usr/bin/yum update -y\n"
我使用的任何方法都匹配换行符,但会将它们转换为换行符而不是\n。因此,这些例子:

sed 's/\n/\n/g' file
sed 's/\n/\\\n/g' file
tr '\n' '\n' <file
tr '\n' "\n" <file

所有这些都会产生与文件本身完全相同的输出。那么,如何匹配换行符并用实际字符串\n替换它,而不是将其本身识别为换行符的内容呢?

在这里,您需要两个字符,斜杠和n来替换单个换行符。因此,tr不是一个好的选择

我不清楚你是否想在双引号前加上反斜杠。下面的答案假设你是这样做的。如果你不这样做,删除这些替换就足够简单了

使用awk 使用sed Perl:


tr无法执行此操作,因为它无法将一个字符\n转换为两个字符的字符串。\n

我确实希望在双引号之前加反斜杠,谢谢。两个答案都有效
$ awk '{gsub(/"/, "\\\""); printf "%s\\n",$0}' file
#!/bin/bash\necho $(date \"+%F %R:%S\") \":: yum update\"\n/usr/bin/yum update -y\n
$ sed ':again; N; $!b again; s/"/\\"/g; s/\n/\\n/g; s/$/\\n/' file
#!/bin/bash\necho $(date \"+%F %R:%S\") \":: yum update\"\n/usr/bin/yum update -y\n
perl -0777 -pe 's/\n/\\n/g; s/"/\\"/g' file