This will sort the file by the length of the line, the longest lines:
cat file.txt | (while read LINE; do echo -e "${#LINE}\t$LINE"; done) | sort -rn | cut -f 2-
This will replace term with _term_ , but will not turn _term_ into __term__ :
sed -r 's/(^|[^_])term([^_]|$)/\1_term_\2/g' sed -r -e 's/(^|[^_])term/\1_term_/g' -e 's/term([^_]|$)/_term_\1/g'
The first will work very well, except that it will skip _term and term_ , mistakenly leaving them alone. Use the second if it is important. Here is my silly test case:
# echo here is _term_ and then a term you terminator haha _terminator and then _term_inator term_inator | sed -re 's/(^|[^_])term([^_]|$)/\1_term_\2/g' here is _term_ and then a _term_ you _term_inator haha _terminator and then _term_inator term_inator
source share