Skip to content
GradedJestRisk edited this page Apr 27, 2024 · 5 revisions

Overview

List:

  • get encoding: file --mime $FILENAME
  • check line ending cat -A $FILENAME (^M$ in Windows and $ in Unix)
  • change line ending (works stdin/out) dos2unix
  • change encoding (works stdin/out) iconv --from-code=ISO-8859-1 --to-code=UTF-8//TRANSLIT $INPUT_FILE --output=$OUTPOUT_FILE
  • list all files from a folder in a file ls [FOLDER] > [FILENAME]
  • delete a line matching a pattern sed -i '/[PATTERN] /d' [FILENAME]
  • add string to start of each line sed -e 's/^/[STRING_TO_ADD]/' -i [FILENAME]

Search

file

find <LOCATION> <CRITERIA> <VALUE>

By name:

  • basic usage : find /usr -name home
  • rejecting permission errors : find / -name home 2>/dev/null
  • extension : find /usr -name "*.sh"
  • case-insensitive: find /usr -iname "*.sh"
  • execute command on result (here, copy to /result): find /usr -iname "*.sh -exec cp {} /result \

Count files

Count files in directory

❯ find dir -type f -iname "*.js" | wc --lines
3

Count lines

LoC in a directory for a filetype

  • detail per file
> find dir -type f -iname "*.js" | xargs wc --lines
3 dir/1.js
1 dir/2.js
3 dir/subdir/sub1.js
7 total
  • total only
> find dir -type f -iname "*.js" | xargs wc --lines | awk '/total/{k+=$1}END{print k," lines of code in folder"}';
7  lines of code in tests folder
  • excluding a directory
find . -type d -iname node_modules -prune -o -type f -iname "*.js" | xargs wc --lines | awk '/total/{k+=$1}END{print k," lines of code in folder"}';
  • per subdirectory (matching pattern)
for each in $(find codebase -maxdepth 1 -type d -iname "prefix_*") ; do 
    (echo "$each" ; find "$each" -type f -name "*.sql" | wc --lines ); 
done

file content

grep <REGEXP> <FILE> <OPTIONS> </code>

Eg:

  • list all lines which contains hello in a file, including line number: grep hello HelloWorld.sh -n
  • show context (lines before and after): -C

Other

List

  • remove duplicates: (..) | uniq e
  • find . -name '<FILENAME_PATTERN>l' -exec grep -l <FILE_CONTENT_PATERN> {} \; | xargs cp -t <TARGET_FOLDER>
  • search for file content + copying matching files grep -l "foo" *.log | xargs cp -t ../files_containing_foo