Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从shell中的文本中提取字符串_Shell_Sh - Fatal编程技术网

如何从shell中的文本中提取字符串

如何从shell中的文本中提取字符串,shell,sh,Shell,Sh,我有一个文件名 "PHOTOS_TIMESTAMP_5373382" 我想从这个文件名“PHOTOS\u 5373382”中提取并添加“ABC”,即最终希望它看起来像 shell脚本中的“abc\U照片” echo“PHOTOS_TIMESTAMP_5373382”| awk-F”{print“ABC_$1”_$3} echo将为awk命令提供输入 awk命令使用选项-F对输入的字符进行数据标记化 可以使用$n访问单个令牌(从1开始),其中n是令牌编号 您需要在shell上直接执行以下命令序列

我有一个文件名

"PHOTOS_TIMESTAMP_5373382"
我想从这个文件名
“PHOTOS\u 5373382”
中提取并添加
“ABC”
,即最终希望它看起来像

shell脚本中的“abc\U照片”

echo“PHOTOS_TIMESTAMP_5373382”| awk-F”{print“ABC_$1”_$3}

echo
将为
awk
命令提供输入

awk
命令使用选项
-F
对输入的字符进行数据标记化


可以使用
$n
访问单个令牌(从1开始),其中
n
是令牌编号

您需要在shell上直接执行以下命令序列,最好是将
bash
shell(or)作为一个完整的脚本,该脚本只需一个参数即可转换文件

#!/bin/bash

myFile="$1"                                            # Input argument (file-name with extension)
filename=$(basename "$myFile")                         # Getting the absolute file-path
extension="${filename##*.}"                            # Extracting the file-name part without extension
filename="${filename%.*}"                              # Extracting the extension part
IFS="_" read -r string1 string2 string3 <<<"$filename" # Extracting the sub-string needed from the original file-name with '_' de-limiter
mv -v "$myFile" ABC_"$string1"_"$string3"."$extension" # Renaming the actual file
虽然我喜欢awk

天然壳溶液

k="PHOTOS_TIMESTAMP_5373382"
IFS="_" read -a arr <<< "$k"
echo abc_${arr[0]}_${arr[2]}

mv照片\u时间戳\u 5373382 abc\u照片\u 5373382
?或者你想说“TIMESTAMP”和“ABC”是一般文本的占位符吗?试试看
cut
命令
sed
是你的朋友吗
k="PHOTOS_TIMESTAMP_5373382"
IFS="_" read -a arr <<< "$k"
echo abc_${arr[0]}_${arr[2]}
echo "abc_$k" | sed -e 's/TIMESTAMP_//g'
abc_PHOTOS_5373382