0

有没有简单的解决方案如何修剪我的文件名中的后缀?问题是,我的后缀长度不同。文件名中只有相同的字符串是_L001。

请参阅示例:

NAME-code_code2_L001_sufix
NAME-code_L001_sufix_sufix2_sufix3
NAME-code_code2_code3_L001_sufix_sufix2_sufix3

我需要在_L001之前输出所有内容:

NAME-code_code2
NAME-code
NAME-code_code2_code3

我正在考虑做这样的事情(当后缀是固定长度时):

echo NAME-code_code2_L001_sufix | rev | cut -c 12- | rev

但当然我的后缀长度是不同的。有没有 bash 或 awk 解决方案?

谢谢你。

4

6 回答 6

4

使用纯字符串操作技术:-

$ string="NAME-code_code2_L001_sufix"; printf "%s\n" "${string%_L001*}"
NAME-code_code2

对于文件中的所有行,您可以bash通过读取内存中的文件并执行提取来执行相同的操作

# Setting a variable to the contents of a file using 'command-substitution'
$ mystringfile="$(<stringfile)"                 

# Read the new-line de-limited string into a bash-array for per-element operation
$ IFS=$'\n' read -d '' -ra inputArray <<< "$mystringfile"

# Run the sub-string extraction for each entry in the array
$ for eachString in "${inputArray[@]}"; do printf "%s\n" "${eachString%_L001*}"; done

NAME-code_code2
NAME-code
NAME-code_code2_code3

printf您可以通过修改for 循环中的内容将内容写入新文件

printf "%s\n" "${eachString%_L001*}" >> output-file
于 2016-10-06T11:52:09.737 回答
2

您可以_L001在 awk 中用作字段分隔符并打印第一个字段:

awk -F '_L001' '{print $1}' file

NAME-code_code2
NAME-code
NAME-code_code2_code3
于 2016-10-06T11:52:00.387 回答
1

我会建议sed

sed 's|\(.*\)_L001.*|\1|'

例子:

$ for LINE in NAME-code_code2_L001_sufix NAME-code_L001_sufix_sufix2_sufix3 NAME-code_code2_code3_L001_sufix_sufix2_sufix3; do echo "$LINE"|sed 's|\(.*\)_L001.*|\1|';done
NAME-code_code2
NAME-code
NAME-code_code2_code3
于 2016-10-06T11:50:21.343 回答
1

这是grep解决方案:这将从一开始就打印行直到_L001被看到。

grep -oP '^.*?(?=_L001)' inputfile
NAME-code_code2
NAME-code
NAME-code_code2_code3
于 2016-10-06T12:33:41.707 回答
1

很多方法可以做到这一点:

# Here is your Input text.
bash$> cat a.txt
NAME-code_code2_L001_sufix
NAME-code_L001_sufix_sufix2_sufix3
NAME-code_code2_code3_L001_sufix_sufix2_sufix3
bash$>

# Desired output using perl.
bash$> cat a.txt |perl -nle 'if (/^(.+)_L.*$/){print $1}'
NAME-code_code2
NAME-code
NAME-code_code2_code3
bash$>

# Desired output using sed.
bash$> cat a.txt |sed 's#\(.*\)_L001_.*#\1#g'
NAME-code_code2
NAME-code
NAME-code_code2_code3
bash$>

# Desired output using cut
bash$> cat a.txt |cut -f1 -d "L"|sed 's/_$//g'
NAME-code_code2
NAME-code
NAME-code_code2_code3
bash$>
于 2016-10-06T14:03:07.950 回答
1

您还可以使用字符串替换,例如:

for i in NAME-code_code2_L001_sufix NAME-code_L001_sufix_sufix2_sufix3 NAME-code_code2_code3_L001_sufix_sufix2_sufix3
do
    echo ${i%_L001*}
done
于 2016-10-06T14:07:30.720 回答