面试题答案
一键面试脚本代码
#!/bin/bash
if [ $# -ne 2 ]; then
echo "Usage: $0 <text_file_path> <word>"
exit 1
fi
text_file=$1
word=$2
sed -n "/\b$word\b/=" $text_file | sed -f <(sed -n "/\b$word\b/{p;=}" $text_file | sed 'N;s/\n/ /') > result.txt
sed -i "/\b$word\b/d" $text_file
sed命令使用解释
-
查找单词所在行的行号:
sed -n "/\b$word\b/=" $text_file
sed -n
选项表示不输出模式空间内容,仅在匹配时输出指定内容。/\b$word\b/
是正则表达式,\b
表示单词边界,确保只匹配完整单词。=
命令用于输出匹配行的行号。 -
获取单词所在行的行号及该行内容:
sed -n "/\b$word\b/{p;=}" $text_file | sed 'N;s/\n/ /'
首先,
sed -n "/\b$word\b/{p;=}" $text_file
匹配包含单词的行,p
打印该行内容,=
输出该行行号,输出结果是行号和内容分两行。然后通过sed 'N;s/\n/ /'
将相邻两行(行号和内容)合并为一行,用空格分隔。 -
将结果输出到result.txt:
sed -n "/\b$word\b/=" $text_file | sed -f <(sed -n "/\b$word\b/{p;=}" $text_file | sed 'N;s/\n/ /') > result.txt
前面两部分命令通过管道连接,将获取的行号和内容输出到
result.txt
文件。 -
在原文件中删除包含单词的行:
sed -i "/\b$word\b/d" $text_file
sed -i
选项表示直接修改原文件,/\b$word\b/d
匹配包含单词的行并删除。