美好的一天!
我在 Ubuntu 中有如下文件:
这是文件“ZAF_MM_CYCLE_K036”的副本,文件代码是K036
文件内容相同
LOADED_AGRS ZAF_MM_CYCLE_K036
AGG_DEFINE 200ZAF_MM_CYCLE_K036 $WERKS K036
AGG_1521 200ZAF_MM_CYCLE_K036
这里我必须根据文件名将code替换为自己的code。
例如:
文件:ZAF_MM_CYCLE_K051.XLS
它的代码是K051,我必须将K036替换为K051,这样文件的内容将是:
LOADED_AGRS ZAF_MM_CYCLE_K051
AGG_DEFINE 200ZAF_MM_CYCLE_K051 $WERKS K051
AGG_1521 200ZAF_MM_CYCLE_K051
有人可以帮忙吗?
正如 Ron 在评论中提到的,您可以使用 bash 执行类似的操作来根据内容生成文件:
# iterate over the values from 036 to 051 and generate a file with that filename as well as contents respective to the indexes.
for i in {036..051}; do
echo "Generating 'ZAF_MM_CYCLE_K${i}.XLS'"
cat > ZAF_MM_CYCLE_K${i}.XLS << EOL
LOADED_AGRS ZAF_MM_CYCLE_K${i}
AGG_DEFINE 200ZAF_MM_CYCLE_K${i} $WERKS K${i}
AGG_1521 200ZAF_MM_CYCLE_K${i}
EOL
done
上面将在当前目录中生成描述的文件。
如果你想使用sed之类的东西来替换内容,你是否需要在文件所在的目录中执行如下操作:
for f in ZAF_MM_CYCLE_K0*.XLS; do
# set a variable based on the file name, using bash parameter expansion to strip off the ZAF_MM_CYCLE_K from the file name
n=${f//ZAF_MM_CYCLE_K/}
echo "replacing K036 in $f with ${n%*.XLS}" # strip the .XLS
# replace the contents with the number found in the file name
sed -i "s|K036|${n%*.XLS}|g" "$f"
done
如果所有文件都包含 K036,下面的脚本将为您提供帮助。
#!/bin/bash
directory="/path/to/file"
cd "$directory"
for file in ZAF_MM_CYCLE_K*.xls; do
code=$(echo "$file" | cut -d'_' -f4 | cut -d'.' -f1)
sed -i "s/K036/$code/g" "$file"
echo "Code replaced in $file"
done
哪里
回显“$文件”|切 -d'_' -f4 |切-d'。' -f1
将从文件名中提取文件名k051
sed -i“s/K036/$code/g”“$file”
将用新值替换旧值
所以这会对您的情况有所帮助。