在linux中有像cat
这样的命令可以从文件中返回指定数量的字符吗?
例如,我有一个文本文件,如:
Hello world
this is the second line
this is the third line
我想要的东西会返回前5个字符,这将是"hello“。
谢谢
发布于 2008-10-20 17:08:39
您可以使用dd来提取任意的字节块。
例如,
dd skip=1234 count=5 bs=1
将字节1235到1239从其输入复制到其输出,并丢弃其余字节。
要仅从标准输入中获取前五个字节,请执行以下操作:
dd count=5 bs=1
请注意,如果您想指定输入文件名,dd具有老式的参数解析,因此您可以这样做:
dd count=5 bs=1 if=filename
另请注意,dd详细地声明了它所做的事情,因此要丢弃它,请执行以下操作:
dd count=5 bs=1 2>&-
或
dd count=5 bs=1 2>/dev/null
发布于 2008-10-20 15:59:38
你也可以用grep把这一行去掉,然后像这样剪掉它:
grep 'text‘filename | cut -c 1-5
发布于 2017-09-09 01:02:40
下面是一个简单的脚本,它使用了这里提到的dd
方法:
extract_chars.sh
#!/usr/bin/env bash
function show_help()
{
IT="
extracts characters X to Y from stdin or FILE
usage: X Y {FILE}
e.g.
2 10 /tmp/it => extract chars 2-10 from /tmp/it
EOF
"
echo "$IT"
exit
}
if [ "$1" == "help" ]
then
show_help
fi
if [ -z "$1" ]
then
show_help
fi
FROM=$1
TO=$2
COUNT=`expr $TO - $FROM + 1`
if [ -z "$3" ]
then
dd skip=$FROM count=$COUNT bs=1 2>/dev/null
else
dd skip=$FROM count=$COUNT bs=1 if=$3 2>/dev/null
fi
https://stackoverflow.com/questions/218912
复制相似问题