简体   繁体   English

在bash脚本中执行cut命令

[英]execute cut command inside bash script

Every line printed with the echo includes the forward slashes for the directories that the given files are in. I am trying to cut the forward slashes using the cut command but it is not working. 回显打印的每一行都包含给定文件所在目录的正斜杠。我正在尝试使用cut命令剪切正斜杠,但它不起作用。 The files are gzipped so they have the .gz extension. 这些文件已压缩,因此具有.gz扩展名。

#!/bin/bash

for filename in /data/logs/2017/month_01/201701*
do
echo $filename
cut $filename -d '/' -f1
done

Thanks in advance. 提前致谢。

The order of commands is wrong. 命令顺序错误。 You need to stream the string input to the cut command via pipe( | ) or here-strings( <<< ). 您需要通过pipe( | )或here-strings( <<< )将输入到cut命令的字符串流式传输

echo "$filename" | cut  -d '/' -f1

(or) (要么)

cut -d '/' -f1 <<<"$filename"

(or) using here-docs (或)使用here-docs

cut -d '/' -f1 <<EOF
$filename
EOF

data 数据

And don't forget to double-quote variables to avoid Word-Splitting done by the shell. 并且不要忘记对变量加双引号,以避免shell进行单词拆分

Assuming filename is /a/b/c.gz you just want c.gz ? 假设文件名是/a/b/c.gz您只需要c.gz

Well there's two very easy answers: 好吧,有两个非常简单的答案:

basename $filename

The other is: 另一个是:

echo ${filename##*/}

The latter make use bash 's built-in string delete parameter expansion. 后者利用bash的内置字符串delete参数扩展。

Another way of solving your problem, is you could change directory first, ie 解决问题的另一种方法是,您可以先更改目录,即

#!/bin/bash

pushd /data/logs/2017/month_01
for filename in 201701* 
do
    echo $filename
done
popd

Reference: 参考:

(EDIT: Fixed typo identified by @123) (编辑:固定错字由@ 123标识)

As suggested b @lnian cut command used with echo command via pipe sign For getting only file name with your script you need to use. 如建议的b @lnian cut命令与通过管道符号的echo命令一起使用要仅使用脚本获取文件名,您需要使用。

cut with -f1 option will get first value before / which would give blank so you need to get last value from the filename. 用-f1选项剪切将在/之前获得第一个值,该值将为空白,因此您需要从文件名中获取最后一个值。

#!/bin/bash

for filename in /data/logs/2017/month_01/201701*
do
echo "$filename" | rev| cut  -d '/' -f1
done

rev command reverse the filename so you will get last value which is your filename rev命令反转文件名,这样您将获得最后一个值,即您的文件名

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

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