'How to replace/rename the headers in a text file?

I had around 10,000 text files in a directory,

  1. I'd like to replace the text file headers with a same keyword (>zebra_cat).

Orginal file

head -n 1 dat.txt
>bghjallshkal

Modified file

head -n 1 dat.txt
>zebra_cat

sed '/^>/ s/.*/>dat/' *.txt

The output generates by sed is an concatenated file, by adding loop, redirected output to a separate output files.

  1. Is it possible to rename the header names with their respective file names ?

Orginal file

head -n 1 dat.txt
>xxxxxxxx ; zxf

Modified file

head -n 1 dat.txt
>dat

Suggestions please!



Solution 1:[1]

This is pretty simple using sed:

#!/bin/bash

filename="dat.txt"   # Or maybe use Command-line parameter ${1}.

if [ ! -f ${filename} ]; then
  echo "'${filename}' is not a file."
  exit 1
elif [ ! -w ${filename} ]; then
  echo "'${filename}' is not writable."
  exit 1
fi

sed -i '1s/^.*$/> '${filename}'/' ${filename}

The -i option tells sed to update the file in-place.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor Lee