簡體   English   中英

刪除文件名中的特定字符

[英]Remove specific characters in filename

有什么簡單的解決方案如何修剪我的文件名中的后綴? 問題是我的后綴長度不同。 文件名中只有相同的字符串是_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解決方案嗎?

謝謝。

使用純字符串操作技術:

$ 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

您可以通過將for循環中的printf修改為新文件,將內容寫入新文件

printf "%s\n" "${eachString%_L001*}" >> output-file

您可以使用_L001作為awk中的字段分隔符並打印第一個字段:

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

NAME-code_code2
NAME-code
NAME-code_code2_code3

我建議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

這是grep解決方案:這將從頭開始打印行,直到看到_L001

grep -oP '^.*?(?=_L001)' inputfile
NAME-code_code2
NAME-code
NAME-code_code2_code3

有很多方法可以做到這一點:

# 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$>

您還可以使用字符串替換 ,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM