我在单个字符和提取数字的示例之前找到了几个提取示例,但我没有找到任何关于在数字之前提取字符的内容。
我的问题: 我看起来像这样的一些字符串:
NUC320 Syllabus Template - 8wk
SLA School Template - UL
CJ101 Syllabus Template - 8wk
TECH201 Syllabus Template - 8wk
Test Clone ID17
如果字符串不包含我想要的数据,我需要跳过它。所需的输出是:
NUC-320
CJ-101
TECH-201
SLA School Template - UL
&将跳过Test Clone ID17
。
我认为这个过程有效:
" "
x
y
$x"-"$y
并分配给另一个变量z
更多信息: 使用循环从几千个文本文档中的一行中提取字符串。它们将用于附加超链接并在循环期间重命名文件。
修改
#!/bin/sh
# my files are named 1.txt through 9999.txt i both
# increments the loop and sets the filename to be searched
i=1
while [ $i -lt 10000 ]
do
x=$(head -n 31 $i.txt | tail -1 | cut -c 7-)
if [ ! -z "$x" -a "$x" != " " ]; then
# I'd like to insert the hyperlink with the output on the
# same line (1.txt;cj101 Syllabus Template - 8wk;www.link.com/cj101)
echo "$i.txt;$x" >> syllabus.txt
# else
# rm $i.txt
fi
i=`expr $i + 1`
sleep .1
done
答案 0 :(得分:1)
打印以大写字母后跟数字开头的行。它还在它们之间添加-
:
sed -n 's/^\([A-Z]\+\)\([0-9]\+\) .*/\1-\2/p' input
给出:
NUC-320
CJ-101
TECH-201
答案 1 :(得分:0)
符合POSIX的awk
解决方案:
awk '{ if (match($1, /[0-9]+$/)) print substr($1, 1, RSTART-1) "-" substr($1, RSTART) }' \
file |
while IFS= read -r token; do
# Process token here (append to hyperlink, ...)
echo "[$token]"
done
awk
用于提取感兴趣的重新格式化的令牌,然后在 shell while loop
中处理。match($1, /[0-9]+$/)
将第一个以空格分隔的字段($1
)与扩展正则表达式[0-9]+$
匹配,即仅当字段以一个或多个数字结尾时才匹配。substr($1, 1, RSTART-1) "-" substr($1, RSTART)
使用-
通过特殊RSTART
变量将第一个数字前的部分与数字运行连接起来,该变量指示最近的{1}字符位置{ {1}}调用匹配。答案 2 :(得分:0)
awk '$1 ~/[0-9]/{sub(/...$/,"-&",$1);print $1}' file
NUC-320
CJ-101
TECH-201