我有很多文件,第一行是标识符。后续行是标识符的产物。以下是该文件的示例:
0G000001:
Product_2221
Product_2222
Product_2122
...
我想将标识符放在文件每行的开头。最终输出将是这样的:
0G000001: Product_2221
0G000001: Product_2222
0G000001: Product:2122
....
我想为我拥有的所有文件制作一个循环。我一直在尝试:
for i in $(echo `head -n1 file.$i.txt);
do
cat - file.$i.txt > file_id.$i.txt;
done
但我只复制文件的第一行。我知道 sed 可以在文件的开头添加特定的文本,但我无法弄明白指定文本是文件的第一行和循环上下文。
答案 0 :(得分:2)
无需显式循环:
int rowLimit = grid.length;
int columnLimit = grid.length;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
for(int x = Math.max(0, i-1); x <= Math.min(i+1, rowLimit); x++) {
for(int y = Math.max(0, j-1); y <= Math.min(j+1, columnLimit); y++) {
if(x != i || y != j) {
adj++;
}
}
}
}
}
System.out.println("Total adjacent:" + ady);
答案 1 :(得分:1)
使用awk
:
awk 'NR==1 { prod = $0 } NR>1 { print prod, $0 }' infile
输出:
0G000001: Product_2221
0G000001: Product_2222
0G000001: Product_2122
答案 2 :(得分:1)
这可能适合你(GNU sed):
sed -ri '1h;1d;G;s/(.*)\n(.*)/\2 \1/' file ...
将第一行保存在保留空间(HS)中,然后将其从模式空间(PS)中删除。对于每一行(除了第一行),将HS附加到PS然后交换行并用空格替换换行符。
答案 3 :(得分:1)
执行所需操作的sed命令可能如下所示:
$ sed '1{h;d};G;s/\(.*\)\n\(.*\)/\2 \1/' infile
0G000001: Product_2221
0G000001: Product_2222
0G000001: Product_2122
执行以下操作:
1 { # On the first line
h # Copy the pattern space to the hold space
d # Delete the line, move to next line
}
G # Append the hold space to the pattern space
s/\(.*\)\n\(.*\)/\2 \1/ # Swap the lines in the pattern space
某些seds可能会抱怨{h;d}
并需要额外的分号{h;d;}
。
要为文件就地执行此操作,您可以使用
sed -i '1{h;d};G;s/\(.*\)\n\(.*\)/\2 \1/' infile
表示GNU sed,或
sed -i '' '1{h;d};G;s/\(.*\)\n\(.*\)/\2 \1/' infile
对于macOS sed。或者,如果您的sed根本不支持-i
:
sed '1{h;d};G;s/\(.*\)\n\(.*\)/\2 \1/' infile > tmpfile && mv tmpfile infile
在循环中对目录中的所有文件执行此操作:
for f in /path/to/dir/*; do
sed -i '1{h;d};G;s/\(.*\)\n\(.*\)/\2 \1/' "$f"
done
甚至直接使用glob:
sed -i '1{h;d};G;s/\(.*\)\n\(.*\)/\2 \1/' /path/to/dir/*
后者适用于GNU sed;不确定其他的seds。
答案 4 :(得分:1)
sed + head 解决方案:
for f in *.txt; do sed -i '1d; s/^/'"$(head -n1 $f)"' /' "$f"; done
-i
- 就地修改文件
1d;
- 删除第1行
$(head -n1 $f)
- 从文件中提取第一行(获取标识符)
s/^/<identifier> /
- 为文件中的每一行添加标识符