簡體   English   中英

Shell腳本修改具有同一目錄中多個文件的文件名的變量

[英]Shell script to modify variable with file name of multiple files in same directory

我在目錄中有多個文件,例如:

a01.txt
a02.txt
a03.txt 
etc...

目錄中所有文本文件的第3行如下:

consumer[location].userid= constant

我想用相應的文件名替換單詞“ location”,而不在每個文件的第三行中擴展名,例如:as

consumer[a01].userid= constant    --------- for a01.txt
consumer[a02].userid= constant    --------- for a03.txt
etc

你能幫忙嗎?

因此,從頂部開始:您想替換文件特定行中的單詞(位置)。 Google說sed可以做到:

sed -i "3s/location/foo/" file.ext

將替換“ file.ext”文件第三行中“ location”的第一次出現

您要替換位置的字符串應該是不帶擴展名的文件名。 由於您知道擴展名,因此basename應該可以正常工作:

basename /path/to/file.ext .ext

將返回“文件”。

現在遍歷目錄中的所有txt文件:

for filename in directory/*.txt; do
# Do stuff
done

合並這些命令將得到一個簡短的腳本,如下所示:

#!/bin/bash
# Assumes the script is located in the data directory
for filename in ./*.txt; do
    name=$(basename $filename .txt)
    echo "$filename -> $name"
    sed -i "3s/location/$name/" $filename
done

暫無
暫無

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

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