如何在ls的输出中使用sed替换变量值

时间:2018-04-13 10:46:15

标签: bash shell

我正在尝试列出4个文件(使用ls),这些文件位于其他目录中。

 path=logs/gh/
 ls -lrt ${path}sample ${path}sample1                                                                                                           
-rw-r--r-- 1 29573 29573 0 Apr 13 10:18 logs/gh/sample                                                                                                
-rw-r--r-- 1 29573 29573 0 Apr 13 10:18 logs/gh/sample1  

但我想按以下方式返回输出

ls -lrt ${path}sample ${path}sample1                                                                                                           
-rw-r--r-- 1 29573 29573 0 Apr 13 10:18 sample                                                                                                
-rw-r--r-- 1 29573 29573 0 Apr 13 10:18 sample1 

我尝试使用sed将$ path替换为null但不使用

ls -lrt ${path}log.txt| sed "s/${path}//g"
sed: -e expression #1, char 11: unknown option to `s'

请告诉我如何实现这一目标......

3 个答案:

答案 0 :(得分:0)

/中有$path个字符,会混淆sed。不过,您可以在sed中使用其他分隔符:sed "s|${path}||g"

这会导致|出现$path的风险,即使不太可能。

为什么不这样做呢:

(cd logs/gh/; ls -lrt sample sample1)

括号将目录的本地更改为其中的命令。

答案 1 :(得分:0)

您的原始命令类似于:

File "/home/dimension/.virtualenvs/docparser/lib/python3.5/site-packages/mongoengine/queryset/transform.py", line 277, in update
    value = field.prepare_query_value(op, value)
  File "/home/dimension/.virtualenvs/docparser/lib/python3.5/site-packages/mongoengine/fields.py", line 708, in prepare_query_value
    return [self.field.prepare_query_value(op, v) for v in value]
  File "/home/dimension/.virtualenvs/docparser/lib/python3.5/site-packages/mongoengine/fields.py", line 708, in <listcomp>
    return [self.field.prepare_query_value(op, v) for v in value]
  File "/home/dimension/.virtualenvs/docparser/lib/python3.5/site-packages/mongoengine/fields.py", line 997, in prepare_query_value
    super(ReferenceField, self).prepare_query_value(op, value)
  File "/home/dimension/.virtualenvs/docparser/lib/python3.5/site-packages/mongoengine/base/fields.py", line 174, in prepare_query_value
    self.validate(value)
  File "/home/dimension/.virtualenvs/docparser/lib/python3.5/site-packages/mongoengine/fields.py", line 1003, in validate
    self.error('A ReferenceField only accepts DBRef or documents')
  File "/home/dimension/.virtualenvs/docparser/lib/python3.5/site-packages/mongoengine/base/fields.py", line 149, in error
    raise ValidationError(message, errors=errors, field_name=field_name)
mongoengine.errors.ValidationError: A ReferenceField only accepts DBRef or documents

可以通过以下方式抑制错误:(1)将ls -lrt ${path}* | sed "s/${path}//g" sed: -e expression #1, char 11: unknown option to `s' 选项添加到-n,(2)将sed替换为/,以及(3)使用{ {1}}标记而不是|

p

答案 2 :(得分:-1)

现在无法测试,但试试这个:

{} Pretty print source