简体   繁体   English

在脚本或 shell 中执行的结果不同

[英]Not same result executing in script or in shell

I am using the following command to remove a line in a file that works partially in script, but completely in shell.我正在使用以下命令删除文件中的一行,该文件部分在脚本中有效,但在 shell 中完全有效。

cat "$folderDb.list" | sed "/^$elementToDeleteKey /d" > "$folderDb.list-d"

The space after $elementToDeleteKey is mandatory because the file is structured as: $elementToDeleteKey后面的空格是强制性的,因为文件的结构如下:

KEY_WITHOUT_SPACES INFO1 INFO2 INFO3...

This code executed in my script removes the line when the key is a file (where spaces were replaced by underscore), but not when it is a folder (same replacement here).当键是文件(空格被下划线替换)时,在我的脚本中执行的这段代码会删除该行,而不是当它是文件夹时(这里的替换相同)。 I know this doesn't matter because in this context they are both considered as strings.我知道这无关紧要,因为在这种情况下,它们都被视为字符串。

This code executed by hand in the shell outputs me the desired result: the line is deleted.在 shell 中手动执行的这段代码输出了我想要的结果:该行被删除。

Input file输入文件

/share/homes/test/test1/backup.conf 4 979 Jan 20 15:02:05 2022 /share/homes/test/test1/backup.conf
/share/homes/test/test1/backups.sh 4 843 Feb 19 23:25:02 2019 /share/homes/test/test1/backups.sh
/share/homes/test/test1/test2 8 4096 Jan 26 11:46:21 2022 /share/homes/test/test1/test2
/share/homes/test/test2 8 4096 Jan 26 11:46:21 2022 /share/homes/test/test2
/share/homes/test/test1 8 4096 Jan 27 12:21:20 2022 /share/homes/test/test1
/share/homes/test/test1/test2/backup.conf 4 324 Mar 17 23:06:42 2016 /share/homes/test/test1/test2/backup.conf

elementToDeleteKey elementToDeleteKey

/share/homes/test/test2 /share/homes/test/test1/test2/backup.conf /share/homes/test/test2 /share/homes/test/test1/test2/backup.conf

First one is a folder and the second one is a file, but as I said, they are both strings in this perspective.第一个是文件夹,第二个是文件,但正如我所说,从这个角度来看,它们都是字符串。

The elementToDeleteKey is backslashed before passing to sed . elementToDeleteKey在传递给sed之前被反斜杠。 So it gives:所以它给出了:

\/share\/homes\/test\/test2 \/share\/homes\/test\/test1\/test2\/backup\.conf \/share\/homes\/test\/test2 \/share\/homes\/test\/test1\/test2\/backup\.conf

I am baffled?我很困惑? Is anyone having an explanation?有人有解释吗?

Finally not found what the issue was, but I fixed it by directly modifying the file instead of creating a new file.最后没有找到问题所在,但我通过直接修改文件而不是创建新文件来修复它。

sed -i "/^$elementToDeleteKey /d" "$folderDb.list"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM