有没有一种“规范”的方法?我一直在使用head-n|tail-1来完成这个任务,但我一直在想是否有一个Bash工具专门从文件中提取一行(或一系列行)。
我所说的“规范”是指一个主要功能就是这样做的程序。
有没有一种“规范”的方法?我一直在使用head-n|tail-1来完成这个任务,但我一直在想是否有一个Bash工具专门从文件中提取一行(或一系列行)。
我所说的“规范”是指一个主要功能就是这样做的程序。
当前回答
哇,所有的可能性!
试试看:
sed -n "${lineNum}p" $file
或者根据您的Awk版本选择其中之一:
awk -vlineNum=$lineNum 'NR == lineNum {print $0}' $file
awk -v lineNum=4 '{if (NR == lineNum) {print $0}}' $file
awk '{if (NR == lineNum) {print $0}}' lineNum=$lineNum $file
(您可能需要尝试nawk或gawk命令)。
是否有一种工具只打印特定的行?不是标准工具之一。然而,sed可能是最接近和最简单的用法。
其他回答
获取第n行(单行)
如果您想要一些以后可以自定义而不必处理bash的东西,可以编译这个c程序,并将二进制文件放到您的自定义二进制文件目录中。这假设您知道如何编辑.bashrc文件相应地(仅当您想要编辑路径变量时),如果您不知道,这是一个有用的链接。
要运行此代码,请使用(假设您将二进制代码命名为“行”)。
line [target line] [target file]
实例
line 2 somefile.txt
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
if(argc != 3){
fprintf(stderr, "line needs a line number and a file name");
exit(0);
}
int lineNumber = atoi(argv[1]);
int counter = 0;
char *fileName = argv[2];
FILE *fileReader = fopen(fileName, "r");
if(fileReader == NULL){
fprintf(stderr, "Failed to open file");
exit(0);
}
size_t lineSize = 0;
char* line = NULL;
while(counter < lineNumber){
getline(&line, &linesize, fileReader);
counter++
}
getline(&line, &lineSize, fileReader);
printf("%s\n", line);
fclose(fileReader);
return 0;
}
EDIT:删除fseek并用while循环替换它
我将上面的一些答案放入了一个简短的bash脚本中,您可以将其放入名为get.sh的文件中,并链接到/usr/local/bin/get(或您喜欢的任何其他名称)。
#!/bin/bash
if [ "${1}" == "" ]; then
echo "error: blank line number";
exit 1
fi
re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
echo "error: line number arg not a number";
exit 1
fi
if [ "${2}" == "" ]; then
echo "error: blank file name";
exit 1
fi
sed "${1}q;d" $2;
exit 0
确保它可通过
$ chmod +x get
将其链接以使其在PATH上可用
$ ln -s get.sh /usr/local/bin/get
如果有多行由\n分隔(通常为新行)。您也可以使用“cut”:
echo "$data" | cut -f2 -d$'\n'
您将从文件中获得第二行-f3给你第三行。
这不是一个bash解决方案,但我发现顶级选择不能满足我的需求,例如,
sed 'NUMq;d' file
速度足够快,但挂了几个小时,没有告诉任何进展。我建议编译这个cpp程序并使用它来查找所需的行。您可以使用g++main.cpp编译它,其中main.cpp是包含以下内容的文件。我得到了一个,并执行了它/a.输出
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string filename;
cout << "Enter filename ";
cin >> filename;
int needed_row_number;
cout << "Enter row number ";
cin >> needed_row_number;
int progress_line_count;
cout << "Enter at which every number of rows to monitor progress ";
cin >> progress_line_count;
char ch;
int row_counter = 1;
fstream fin(filename, fstream::in);
while (fin >> noskipws >> ch) {
int ch_int = (int) ch;
if (row_counter == needed_row_number) {
cout << ch;
}
if (ch_int == 10) {
if (row_counter == needed_row_number) {
return 0;
}
row_counter++;
if (row_counter % progress_line_count == 0) {
cout << "Progress: line " << row_counter << endl;
}
}
}
return 0;
}
使用其他人提到的内容,我希望这是我的bash shell中一个快速而出色的函数。
创建文件:~/.functions
添加内容:
getline(){行=$1sed$line'q;2美元}
然后将其添加到~/.bash_profile中:
source~/.函数
现在,当您打开一个新的bash窗口时,您可以这样调用函数:
获取行441 myfile.txt